import { defineStore } from "pinia";
import { getToken, removeToken, setToken } from "../utils/token-utils";
import type { UserInfoState } from "./interface";
import { allAsyncRoutes, anyRoute, staticRoutes } from "@/router/routes";
import { reqLogin, reqLogout, reqUserInfo } from "@/api/user";
import type { RouteRecordRaw } from "vue-router";
import router from "@/router";
import { cloneDeep } from "lodash";

function filterAsyncRoutes(
  allAsyncRoutes: RouteRecordRaw[],
  routeNames: string[]
) {
  return allAsyncRoutes.filter((item) => {
    if (routeNames.indexOf(item.name as string) !== -1) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoutes(item.children, routeNames);
      }
      return true;
    }
  });
}

function addRoutes(routes: RouteRecordRaw[]) {
  // router里原来就已经有了staticRoutes也就是静态路由，所以我只需要将动态和任意追加上去就可以了
  routes.forEach((route) => {
    // 在原来的路由中，动态的将每一个新的路由配置项进行动态的添加
    router.addRoute(route);
  });
}
/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore("userInfo", {
  state: (): UserInfoState => ({
    token: getToken() as string,
    userInfo: {
      routes: [],
      buttons: [],
      roles: [],
      name: "",
      avatar: "",
    },
    menuRoutes: staticRoutes,
  }),

  actions: {
    async login(username: string, password: string) {
      //默认login返回成功promise,失败,返回失败的promise
      try {
        const re = await reqLogin({ username, password });
        //设置token本地存储
        setToken(re.token);
        //把token放在state中
        this.token = re.token;
      } catch (e) {
        return Promise.reject(e);
      }
    },

    // getInfo() {
    //   return new Promise((resolve, reject) => {
    //     setTimeout(() => {
    //       this.name = "admin";
    //       this.avatar =
    //         "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif";
    //       this.menuRoutes = staticRoutes;
    //       resolve({ name: this.name, avatar: this.avatar, token: this.token });
    //     }, 1000);
    //   });
    // },

    async getInfo() {
      try {
        const re = await reqUserInfo();
        this.userInfo = re;
        const arrRoutes = this.userInfo.routes.map((item) => {
          return item.toLocaleLowerCase();
        });
        const asyncRoutes = filterAsyncRoutes(
          cloneDeep(allAsyncRoutes),
          arrRoutes
        );

        // 修改menuRoutes数据，让最新的路由器当中注册的路由数组
        this.menuRoutes = [...staticRoutes, ...asyncRoutes, anyRoute];
        // 路由的跳转
        addRoutes([...asyncRoutes, anyRoute]);
      } catch (e) {
        return Promise.reject(e);
      }
    },

    async logout() {
      try {
        // 退出请求
        await reqLogout();
        // 调用自己封装的reset方法
        this.reset();
      } catch (e) {
        return Promise.reject(e);
      }
    },
    reset() {
      // 删除local中保存的token
      removeToken();
      // 提交重置用户信息的mutation
      this.token = "";
      this.userInfo = {
        routes: [],
        buttons: [],
        roles: [],
        name: "",
        avatar: "",
      };
    },
  },
});
